package com.cy.mall.service.customer.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import com.cy.mall.dao.mapper.customer.*;
import com.cy.mall.model.PageBean;
import com.cy.mall.model.ao.customer.*;
import com.cy.mall.model.domain.customer.*;
import com.cy.mall.model.dto.customer.IdCardOcrResultSaveDTO;
import com.cy.mall.model.dto.fujue.req.AuthDataDTO;
import com.cy.mall.model.dto.fujue.resp.AuthStatusRespDTO;
import com.cy.mall.model.enums.ResultCode;
import com.cy.mall.model.enums.customer.CustomerIdCardAuthStatus;
import com.cy.mall.model.enums.customer.CustomerImageType;
import com.cy.mall.model.query.customer.CustomerInviteListQuery;
import com.cy.mall.model.vo.customer.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.cy.mall.comm.constant.Constants;
import com.cy.mall.comm.utils.CommonUtils;
import com.cy.mall.comm.utils.JsonObjectMapper;
import com.cy.mall.dao.mapper.xiaoan.XiaoanCreditCheckRecordMapper;
import com.cy.mall.model.Result;
import com.cy.mall.model.domain.xiaoan.XiaoanCreditCheckRecord;
import com.cy.mall.model.dto.customer.CustomerLoginDTO;
import com.cy.mall.model.dto.customer.ValidateBigDataResultDTO;
import com.cy.mall.model.dto.customer.ValidateFaceIdResultDTO;
import com.cy.mall.model.dto.xiaoan.XiaoanCreditCheckRecordNotifyDTO;
import com.cy.mall.model.dto.xiaoan.XiaoanNotifyResult;
import com.cy.mall.model.enums.CheckResult;
import com.cy.mall.service.BaseService;
import com.cy.mall.service.customer.CustomerService;

import lombok.extern.slf4j.Slf4j;



/**
 * 客户模块服务
 *
 * @author tanyilin
 *
 * @create 2019年2月25日 下午3:39:39
 */
@Slf4j
@Service
public class CustomerServiceImpl extends BaseService implements CustomerService {

	@Autowired
	private RedisTemplate redisTemplate;
	@Autowired
	private CustomerMapper customerMapper;
	@Autowired
	private CustomerContactMapper customerContactMapper;
	@Autowired
	private CustomerImageMapper customerImageMapper;
	@Autowired
	private CustomerThirdCheckInfoMapper customerThirdCheckInfoMapper;
	@Autowired
	private XiaoanCreditCheckRecordMapper xiaoanCreditCheckRecordMapper;
	@Autowired
	private CustomerInviteMapper customerInviteMapper;
	@Autowired
	private CustomerIdCardAuthRecordMapper customerIdCardAuthRecordMapper;
	@Autowired
	private CustomerHouseInfoMapper customerHouseInfoMapper;
	@Autowired
	private CustomerBankMapper customerBankMapper;
	
	
	@Override
	@Transactional
	public Result login(CustomerLoginAO loginAO) {
		
		Date time = new Date();
		String mobile = loginAO.getMobile();
		
		//查询客户信息
		CustomerLoginDTO customerLoginDTO = customerMapper.queryLogin(mobile);
		
		if(customerLoginDTO == null) {
			//如果客户不存在，则新注册一个客户
			Customer newCustomer = new Customer();
			newCustomer.setMobile(mobile);
			newCustomer.setNickName("昵称".concat(UUID.randomUUID().toString().substring(0, 6)));
			newCustomer.setPassword(CommonUtils.md5Passwod(Constants.INIT_PASSWORD));
			newCustomer.setSource(Constants.CUSTOMER_SOURCE_BANKMA_MALL);
			newCustomer.setCreateTime(time);
			newCustomer.setUpdateTime(time);
			customerMapper.insertSelective(newCustomer);
			
			//初始化新增客户第三方查询信息
			CustomerThirdCheckInfo newCustomerThirdCheckInfo = new CustomerThirdCheckInfo();
			newCustomerThirdCheckInfo.setCustomerId(newCustomer.getId());
			newCustomerThirdCheckInfo.setBigDataCheckResult(CheckResult.UNCHECKED);
			newCustomerThirdCheckInfo.setFaceidCheckResult(CheckResult.UNCHECKED);
			newCustomerThirdCheckInfo.setCreateTime(time);
			newCustomerThirdCheckInfo.setUpdateTime(time);
			customerThirdCheckInfoMapper.insertSelective(newCustomerThirdCheckInfo);

			if(!CommonUtils.isEmpty(loginAO.getInviteCustomerMobile())) {
				//如果邀请人手机号码不为空，则建立邀请关系
				Customer inviteCustomer = new Customer();
				inviteCustomer.setMobile(loginAO.getInviteCustomerMobile());
				inviteCustomer = customerMapper.selectOne(inviteCustomer);
				state(inviteCustomer != null, "邀请人手机号码有误，不存在该客户");

				CustomerInvite newCustomerInvite = new CustomerInvite();
				newCustomerInvite.setCustomerId(newCustomer.getId());
				newCustomerInvite.setInviteCustomerId(inviteCustomer.getId());
				newCustomerInvite.setCreateTime(time);
				newCustomerInvite.setUpdateTime(time);
				customerInviteMapper.insertSelective(newCustomerInvite);

			}
			
			//得到新注册客户的登录信息
			customerLoginDTO = new CustomerLoginDTO();
			customerLoginDTO.setCustomerId(newCustomer.getId());
			customerLoginDTO.setFaceidCheckResult(CheckResult.UNCHECKED);
			customerLoginDTO.setMobile(mobile);
			customerLoginDTO.setNickName(newCustomer.getNickName());
			
		}
		
		if(CommonUtils.isEmpty(customerLoginDTO.getFaceidCheckResult())) {
			//如果FaceidCheckResult == null ,则说明没有初始化客户第三方查询结果信息，则新增一条初始化数据
			CustomerThirdCheckInfo newCustomerThirdCheckInfo = new CustomerThirdCheckInfo();
			newCustomerThirdCheckInfo.setCustomerId(customerLoginDTO.getCustomerId());
			newCustomerThirdCheckInfo.setBigDataCheckResult(CheckResult.UNCHECKED);
			newCustomerThirdCheckInfo.setFaceidCheckResult(CheckResult.UNCHECKED);
			newCustomerThirdCheckInfo.setCreateTime(time);
			newCustomerThirdCheckInfo.setUpdateTime(time);
			customerThirdCheckInfoMapper.insertSelective(newCustomerThirdCheckInfo);
			customerLoginDTO.setFaceidCheckResult(CheckResult.UNCHECKED);
		}
		
		//生成随机token
		String token = UUID.randomUUID().toString();
		//拼凑key
		String key = Constants.CUSTOMER_LOGIN_KEY.concat(token);
		customerLoginDTO.setToken(token);
		//把客户登录信息存到redis
		redisTemplate.opsForValue().set(key, customerLoginDTO, Constants.LOGIN_TIME, Constants.LOGIN_TIME_UNIT);
		
		return Result.success("登录成功", customerLoginDTO);
	}

	@Override
	@Transactional
	public void updateBizToken(Long customerId, String bizToken) {
		
		int result = customerThirdCheckInfoMapper.updateBizToken(customerId, bizToken);
		
		state(result == 1, "更新客户bizToken异常，请刷新页面重新进行操作");
		
	}

	@Override
	@Transactional
	public void saveFaceIdCheckResult(Map<String, Object> textMap, String bizToken) {
		
		Date time = new Date();
		
		String responseJson = JsonObjectMapper.toJson(textMap);
		Integer errCode = textMap.get("ErrCode") == null ? null : Integer.parseInt(textMap.get("ErrCode").toString());
		String errMsg = textMap.get("ErrMsg") == null ? null : textMap.get("ErrMsg").toString();
		String idCard = textMap.get("IdCard") == null ? null : textMap.get("IdCard").toString();
		String name = textMap.get("Name") == null ? null : textMap.get("Name").toString();
		String ocrAddress = textMap.get("OcrAddress") == null ? null : textMap.get("OcrAddress").toString();
		String sim = textMap.get("Sim") == null ? null : textMap.get("Sim").toString();
		
		CustomerThirdCheckInfo dbCustomerThirdCheckInfo = new CustomerThirdCheckInfo();
		dbCustomerThirdCheckInfo.setFaceidCheckBizToken(bizToken);
		dbCustomerThirdCheckInfo = customerThirdCheckInfoMapper.selectOne(dbCustomerThirdCheckInfo);
		state(dbCustomerThirdCheckInfo != null, "获取客户第三方查询结果信息表异常");
		
		CustomerThirdCheckInfo updateCustomerThirdCheckInfo = new CustomerThirdCheckInfo();
		updateCustomerThirdCheckInfo.setId(dbCustomerThirdCheckInfo.getId());
		updateCustomerThirdCheckInfo.setFaceidCheckResult(CheckResult.PASS);
		if(0 != errCode.intValue()) {
			updateCustomerThirdCheckInfo.setFaceidCheckResult(CheckResult.NOT_PASS);
		}
		updateCustomerThirdCheckInfo.setFaceidCheckResultCode(errCode.toString());
		updateCustomerThirdCheckInfo.setFaceidCheckResultMessage(errMsg);
		updateCustomerThirdCheckInfo.setFaceidCheckConfidence(sim);
		updateCustomerThirdCheckInfo.setFaceidCheckResponseJson(responseJson);
		updateCustomerThirdCheckInfo.setUpdateTime(time);
		customerThirdCheckInfoMapper.updateByPrimaryKeySelective(updateCustomerThirdCheckInfo);
		
		Customer updateCustomer = new Customer();
		updateCustomer.setId(dbCustomerThirdCheckInfo.getCustomerId());
		updateCustomer.setName(name);
		updateCustomer.setIdNo(idCard);
		updateCustomer.setSex(CommonUtils.getSexByIdNo(idCard));
		updateCustomer.setIdAddress(ocrAddress);
		updateCustomer.setUpdateTime(time);
		customerMapper.updateByPrimaryKeySelective(updateCustomer);
		
	}

	@Override
	public ValidateFaceIdResultDTO validateFaceIdResult(Long customerId) {
		
		ValidateFaceIdResultDTO validateFaceIdResultDTO = customerMapper.selectValidateFaceIdResultDTO(customerId);
		state(validateFaceIdResultDTO != null, "验证客户是否已完成人脸识别，异常");
		
		return validateFaceIdResultDTO;
	}
	
	@Override
	public ValidateBigDataResultDTO validateBigDataResult(Long customerId) {
		ValidateBigDataResultDTO validateBigDataResultDTO = customerMapper.selectValidateBigDataResultDTO(customerId);
		state(validateBigDataResultDTO != null, "验证客户大数据查询结果，异常");
		
		return validateBigDataResultDTO;
	}

	@Override
	public Customer selectCustomerByPrimaryKey(Long customerId) {
		Customer customer = customerMapper.selectByPrimaryKey(customerId);
		state(customer != null, "获取客户信息异常");
		return customer;
	}

	@Override
	@Transactional
	public void updateCustomer(Customer customer) {
		customer.setUpdateTime(new Date());
		customerMapper.updateByPrimaryKeySelective(customer);
	}

	@Override
	@Transactional
	public Result judgeBigDataCheckResult(Map<String, Object> dataMap, Long customerId) {
		log.info("客户（customerId = {}）大数据结果判定 开始 =================", customerId);
		Map<String, Object> data = (Map) dataMap.get("data");
		List<Map<String, Object>> totalCounts = (ArrayList<Map<String,Object>>) data.get("totalCounts");
		List<Map<String, Object>> list = (ArrayList<Map<String,Object>>) data.get("list");
		
		//判定结果
		boolean isPass = true;
		for(Map<String, Object> bean : totalCounts) {
			
			String blackType = bean.get("blackType").toString();
			Integer blackCount = Integer.parseInt(bean.get("blackCount").toString());
			
			switch (blackType) {
				case "A":
					//严重违法
					if(blackCount > 0) {
						isPass = false;
					}
					break;
				case "B":
					//信贷逾期
					if(blackCount > 0) {
						isPass = false;
					}
					break;
				case "C":
					//法院涉诉
					if(blackCount > 0) {
						isPass = false;
					}
					break;
				case "D":
					//潜在风险
					if(blackCount > 2) {
						isPass = false;
					}
					break;
				default:
					break;
			}
			
		}

		//解析黑名单事件代码
		String blackFactsCode = "";
		for(Map<String, Object> bean : list) {
			String blackFactsType = bean.get("blackFactsType").toString();
			blackFactsCode = blackFactsCode.concat(blackFactsType);
		}

		//更新数据库
		CustomerThirdCheckInfo dbCustomerThirdCheckInfo = new CustomerThirdCheckInfo();
		dbCustomerThirdCheckInfo.setCustomerId(customerId);
		dbCustomerThirdCheckInfo = customerThirdCheckInfoMapper.selectOne(dbCustomerThirdCheckInfo);
		state(dbCustomerThirdCheckInfo != null, "获取客户第三方查询结果信息表异常");
		
		CustomerThirdCheckInfo updateCustomerThirdCheckInfo = new CustomerThirdCheckInfo();
		updateCustomerThirdCheckInfo.setId(dbCustomerThirdCheckInfo.getId());
		updateCustomerThirdCheckInfo.setBlackFactsCode(blackFactsCode);
		updateCustomerThirdCheckInfo.setBigDataCheckResponseJson(JsonObjectMapper.toJson(dataMap));
		updateCustomerThirdCheckInfo.setUpdateTime(new Date());
		if(!isPass) {
			//判定结果：不通过
			updateCustomerThirdCheckInfo.setBigDataCheckResult(CheckResult.NOT_PASS);
			customerThirdCheckInfoMapper.updateByPrimaryKeySelective(updateCustomerThirdCheckInfo);
			log.info("客户（customerId = {}）大数据结果判定：不通过", customerId);
			return Result.fail("客户大数据结果判定：不通过");
		}
		//判定结果：通过
		updateCustomerThirdCheckInfo.setBigDataCheckResult(CheckResult.PASS);
		customerThirdCheckInfoMapper.updateByPrimaryKeySelective(updateCustomerThirdCheckInfo);
		log.info("客户（customerId = {}）大数据结果判定：通过", customerId);
		
		return Result.success("客户大数据结果判定：通过", blackFactsCode);
	}

	@Override
	@Transactional
	public XiaoanNotifyResult handleXiaoanCreditCheckNotify(XiaoanCreditCheckRecordNotifyDTO notifyDTO) {
		
		Date time = new Date();
		Long customerId = 0L;
		
		//1.验证客户手机号码是否已存在,更新客户信息
		Customer dbCustomer = new Customer();
		dbCustomer.setMobile(notifyDTO.getMobile());
		dbCustomer = customerMapper.selectOne(dbCustomer);
		if(dbCustomer == null) {
			//如果客户不存在，则新注册一个客户
			Customer newCustomer = new Customer();
			newCustomer.setMobile(notifyDTO.getMobile());
			newCustomer.setName(notifyDTO.getName());
			newCustomer.setIdNo(notifyDTO.getIdCard());
			newCustomer.setSex(CommonUtils.getSexByIdNo(notifyDTO.getIdCard()));
			newCustomer.setPassword(CommonUtils.md5Passwod(Constants.INIT_PASSWORD));
			newCustomer.setSource(Constants.CUSTOMER_SOURCE_BANKMA_MALL);
			newCustomer.setCreateTime(time);
			newCustomer.setUpdateTime(time);
			customerMapper.insertSelective(newCustomer);
			customerId = newCustomer.getId();
			
		}else {
			//客户已存在
			customerId = dbCustomer.getId();
			Customer updateCustomer = new Customer();
			updateCustomer.setId(customerId);
			updateCustomer.setName(notifyDTO.getName());
			updateCustomer.setIdNo(notifyDTO.getIdCard());
			updateCustomer.setSex(CommonUtils.getSexByIdNo(notifyDTO.getIdCard()));
			updateCustomer.setUpdateTime(time);
			customerMapper.updateByPrimaryKeySelective(updateCustomer);
			
		}
		
		//2.更新客户第三方查询信息
		CustomerThirdCheckInfo dbCustomerThirdCheckInfo = new CustomerThirdCheckInfo();
		dbCustomerThirdCheckInfo.setCustomerId(customerId);
		dbCustomerThirdCheckInfo = customerThirdCheckInfoMapper.selectOne(dbCustomerThirdCheckInfo);
		if(dbCustomerThirdCheckInfo == null) {
			//如果客户第三方查询信息不存在，则新增一个
			//新增客户第三方查询信息
			CustomerThirdCheckInfo newCustomerThirdCheckInfo = new CustomerThirdCheckInfo();
			newCustomerThirdCheckInfo.setCustomerId(customerId);
			if(notifyDTO.getBizStatus() == 1) {
				//小安评估已完成
				newCustomerThirdCheckInfo.setBigDataCheckResult(CheckResult.PASS);
			}else {
				newCustomerThirdCheckInfo.setBigDataCheckResult(CheckResult.UNCHECKED);
			}
			//小安信用星级
			newCustomerThirdCheckInfo.setXiaoanStar(notifyDTO.getStar());
			if("OK".equals(notifyDTO.getFaceVerifyStatus())) {
				//完成了人脸验证流程
				if(notifyDTO.getFaceVerifyResult() == 1) {
					//人脸验证通过
					newCustomerThirdCheckInfo.setFaceidCheckResult(CheckResult.PASS);
				}else {
					//人脸验证不通过
					newCustomerThirdCheckInfo.setFaceidCheckResult(CheckResult.NOT_PASS);
				}
			}else {
				//未完成人脸验证流程
				newCustomerThirdCheckInfo.setFaceidCheckResult(CheckResult.UNCHECKED);
			}
			newCustomerThirdCheckInfo.setFaceidCheckResultMessage(notifyDTO.getErrorMessage());
			newCustomerThirdCheckInfo.setFaceidCheckConfidence(CommonUtils.isEmpty(notifyDTO.getVerifyResultFaceidConfidence()) ? CommonUtils.isEmpty(notifyDTO.getVerifyResultIdPhotoConfidence()) ? null : notifyDTO.getVerifyResultIdPhotoConfidence().toString() : notifyDTO.getVerifyResultFaceidConfidence().toString());
			newCustomerThirdCheckInfo.setCreateTime(time);
			newCustomerThirdCheckInfo.setUpdateTime(time);
			customerThirdCheckInfoMapper.insertSelective(newCustomerThirdCheckInfo);
			
		}else {
			//如果客户第三方查询信息已存在，则更新信息
			if(notifyDTO.getBizStatus() == 1) {
				//小安评估已完成
				dbCustomerThirdCheckInfo.setBigDataCheckResult(CheckResult.PASS);
			}else {
				dbCustomerThirdCheckInfo.setBigDataCheckResult(CheckResult.UNCHECKED);
			}
			//小安信用星级
			dbCustomerThirdCheckInfo.setXiaoanStar(notifyDTO.getStar());
			if("OK".equals(notifyDTO.getFaceVerifyStatus())) {
				//完成了人脸验证流程
				if(notifyDTO.getFaceVerifyResult() == 1) {
					//人脸验证通过
					dbCustomerThirdCheckInfo.setFaceidCheckResult(CheckResult.PASS);
				}else {
					//人脸验证不通过
					dbCustomerThirdCheckInfo.setFaceidCheckResult(CheckResult.NOT_PASS);
				}
			}else {
				//未完成人脸验证流程
				dbCustomerThirdCheckInfo.setFaceidCheckResult(CheckResult.UNCHECKED);
			}
			dbCustomerThirdCheckInfo.setFaceidCheckResultMessage(notifyDTO.getErrorMessage());
			dbCustomerThirdCheckInfo.setFaceidCheckConfidence(CommonUtils.isEmpty(notifyDTO.getVerifyResultFaceidConfidence()) ? CommonUtils.isEmpty(notifyDTO.getVerifyResultIdPhotoConfidence()) ? null : notifyDTO.getVerifyResultIdPhotoConfidence().toString() : notifyDTO.getVerifyResultFaceidConfidence().toString());
			dbCustomerThirdCheckInfo.setUpdateTime(time);
			customerThirdCheckInfoMapper.updateByPrimaryKeySelective(dbCustomerThirdCheckInfo);
			
		}
		
		//3.保存小安评级结果记录表
		XiaoanCreditCheckRecord dbXiaoanCreditCheckRecord = new XiaoanCreditCheckRecord();
		dbXiaoanCreditCheckRecord.setBizNo(notifyDTO.getBizNo());
		dbXiaoanCreditCheckRecord = xiaoanCreditCheckRecordMapper.selectOne(dbXiaoanCreditCheckRecord);
		if(dbXiaoanCreditCheckRecord == null) {
			//如果bizNo不存在，则说明是第一次回调，时间点：在客户完成刷脸流程后会回调
			XiaoanCreditCheckRecord newXiaoanCreditCheckRecord = new XiaoanCreditCheckRecord();
			BeanUtils.copyProperties(notifyDTO, newXiaoanCreditCheckRecord);
			newXiaoanCreditCheckRecord.setCustomerId(customerId);
			newXiaoanCreditCheckRecord.setIdNo(notifyDTO.getIdCard());
			newXiaoanCreditCheckRecord.setCreateTime(time);
			newXiaoanCreditCheckRecord.setUpdateTime(time);
			xiaoanCreditCheckRecordMapper.insertSelective(newXiaoanCreditCheckRecord);
		}else {
			//如果bizNo已存在，则更新之前保存的记录
			BeanUtils.copyProperties(notifyDTO, dbXiaoanCreditCheckRecord);
			dbXiaoanCreditCheckRecord.setIdNo(notifyDTO.getIdCard());
			dbXiaoanCreditCheckRecord.setUpdateTime(time);
			xiaoanCreditCheckRecordMapper.updateByPrimaryKeySelective(dbXiaoanCreditCheckRecord);
		}
		
		return XiaoanNotifyResult.success("请求成功", null);
	}

    @Override
    public CustomerMyInfoVO selectCustomerMyInfoVO(Long customerId) {
		CustomerMyInfoVO result = customerMapper.selectCustomerMyInfoVO(customerId);
		return result;
    }

    @Override
    public PageBean<CustomerInviteListVO> selectCustomerInviteList(CustomerInviteListQuery query) {

		int total = customerInviteMapper.selectCustomerInviteListCount(query);
		List<CustomerInviteListVO> list = new ArrayList<>();
		if(total > 0) {
			query.startPage();
			list = customerInviteMapper.selectCustomerInviteList(query);
			list.stream().forEach(c -> {
				c.setMobile(CommonUtils.mobileFormat(c.getMobile()));
			});
		}

		return new PageBean<>(list, total);
    }

    @Override
    public CustomerIdCardInfoVO getCustomerIdCardInfo(Long customerId) {

		CustomerIdCardInfoVO customerIdCardInfo = customerIdCardAuthRecordMapper.selectCustomerIdCardInfo(customerId);

		return customerIdCardInfo;
    }

    @Override
    public Result validateIdCardResult(Long customerId) {

		//查询数据库
		CustomerIdCardAuthRecord dbCustomerIdCardAuthRecord = new CustomerIdCardAuthRecord();
		dbCustomerIdCardAuthRecord.setCustomerId(customerId);
		dbCustomerIdCardAuthRecord = customerIdCardAuthRecordMapper.selectOne(dbCustomerIdCardAuthRecord);
		if(dbCustomerIdCardAuthRecord == null) {
			//如果为空，说明客户未进行过身份证图片信息上传ocr识别
			return Result.success("客户未完成实名实人验证", ResultCode.CUSTOMER_ID_CARD_UNAUTH);
		}
		//不为空
		//已成功完成认证
		if(CustomerIdCardAuthStatus.AUTH_SUCCESS.equals(dbCustomerIdCardAuthRecord.getAuthStatus())) {
			return Result.success("客户已完成实名实人验证", ResultCode.CUSTOMER_ID_CARD_AUTH_SUCCESS);
		}
		//客户身份证认证失败次数超过（包含）3次
//		if(dbCustomerIdCardAuthRecord.getAuthFailCount() >= 3) {
//			return Result.success("客户身份证认证失败次数超过（包含）3次", ResultCode.CUSTOMER_ID_CARD_AUTH_FAIL_COUNT_GT_3);
//		}
		//以上都不满足，则说明未完成认证、或者认证失败，全部认为 '未完成认证'
		return Result.success("客户未完成实名实人验证", ResultCode.CUSTOMER_ID_CARD_UNAUTH);
    }

    @Override
	@Transactional
    public void doSaveIdCardOcrResult(IdCardOcrResultSaveDTO idCardOcrResultSaveDTO, CustomerImageAddAO imageAddAO, Long customerId) {

		Date time = new Date();

		//先保存身份证图片,先删再增
		CustomerImage delCustomerImage = new CustomerImage();
		delCustomerImage.setCustomerId(customerId);
		delCustomerImage.setType(imageAddAO.getType());
		customerImageMapper.delete(delCustomerImage);

		CustomerImage newCustomerImage = new CustomerImage();
		BeanUtils.copyProperties(imageAddAO, newCustomerImage);
		newCustomerImage.setCustomerId(customerId);
		newCustomerImage.setCreateTime(time);
		newCustomerImage.setUpdateTime(time);
		customerImageMapper.insertSelective(newCustomerImage);

		//保存ocr识别结果信息
		CustomerIdCardAuthRecord dbCustomerIdCardAuthRecord = new CustomerIdCardAuthRecord();
		dbCustomerIdCardAuthRecord.setCustomerId(customerId);
		dbCustomerIdCardAuthRecord = customerIdCardAuthRecordMapper.selectOne(dbCustomerIdCardAuthRecord);
		if(dbCustomerIdCardAuthRecord == null) {
			//如果为空，则新增
			CustomerIdCardAuthRecord newCustomerIdCardAuthRecord = new CustomerIdCardAuthRecord();
			if(CustomerImageType.ID_CARD_FACE.equals(imageAddAO.getType())) {
				//人像面
				//新增认证记录之前，先验证该身份证号码是否已存在
				CustomerIdCardAuthRecord dbCustomerIdCardAuthRecord2 = new CustomerIdCardAuthRecord();
				dbCustomerIdCardAuthRecord2.setIdNo(idCardOcrResultSaveDTO.getNum());
				dbCustomerIdCardAuthRecord2 = customerIdCardAuthRecordMapper.selectOne(dbCustomerIdCardAuthRecord2);
				state(dbCustomerIdCardAuthRecord2 == null, "该身份证号码已存在，请重新上传。");
				//如果不存在，则正常保存
				newCustomerIdCardAuthRecord.setName(idCardOcrResultSaveDTO.getName());
				newCustomerIdCardAuthRecord.setSex(CommonUtils.getSexByText(idCardOcrResultSaveDTO.getSex()));
				newCustomerIdCardAuthRecord.setIdNo(idCardOcrResultSaveDTO.getNum());
				newCustomerIdCardAuthRecord.setNationality(idCardOcrResultSaveDTO.getNationality());
				newCustomerIdCardAuthRecord.setAddress(idCardOcrResultSaveDTO.getAddress());
				newCustomerIdCardAuthRecord.setBirth(CommonUtils.parseDate2(idCardOcrResultSaveDTO.getBirth()));
			}
			newCustomerIdCardAuthRecord.setCustomerId(customerId);
			newCustomerIdCardAuthRecord.setAuthStatus(CustomerIdCardAuthStatus.UNAUTH);
			newCustomerIdCardAuthRecord.setAuthFailCount(0);
			newCustomerIdCardAuthRecord.setCreateTime(time);
			newCustomerIdCardAuthRecord.setUpdateTime(time);
			customerIdCardAuthRecordMapper.insertSelective(newCustomerIdCardAuthRecord);

		}else {
			//若存在，则更新信息
			CustomerIdCardAuthRecord updateCustomerIdCardAuthRecord = new CustomerIdCardAuthRecord();
			if(CustomerImageType.ID_CARD_FACE.equals(imageAddAO.getType())) {
				//人像面
				//若新的身份证号码与在库的身份证号码不一样，则判断新的身份证号码是否也存在
				if(!dbCustomerIdCardAuthRecord.getIdNo().equals(idCardOcrResultSaveDTO.getNum())) {
					CustomerIdCardAuthRecord dbCustomerIdCardAuthRecord2 = new CustomerIdCardAuthRecord();
					dbCustomerIdCardAuthRecord2.setIdNo(idCardOcrResultSaveDTO.getNum());
					dbCustomerIdCardAuthRecord2 = customerIdCardAuthRecordMapper.selectOne(dbCustomerIdCardAuthRecord2);
					state(dbCustomerIdCardAuthRecord2 == null, "该身份证号码已存在，请重新上传。");
				}
				updateCustomerIdCardAuthRecord.setName(idCardOcrResultSaveDTO.getName());
				updateCustomerIdCardAuthRecord.setSex(CommonUtils.getSexByText(idCardOcrResultSaveDTO.getSex()));
				updateCustomerIdCardAuthRecord.setIdNo(idCardOcrResultSaveDTO.getNum());
				updateCustomerIdCardAuthRecord.setNationality(idCardOcrResultSaveDTO.getNationality());
				updateCustomerIdCardAuthRecord.setAddress(idCardOcrResultSaveDTO.getAddress());
				updateCustomerIdCardAuthRecord.setBirth(CommonUtils.parseDate2(idCardOcrResultSaveDTO.getBirth()));
			}
			if(CustomerImageType.ID_CARD_BACK.equals(imageAddAO.getType())) {
				//国徽面
				updateCustomerIdCardAuthRecord.setAuthority(idCardOcrResultSaveDTO.getIssue());
				updateCustomerIdCardAuthRecord.setValidityStartDate(CommonUtils.parseDate2(idCardOcrResultSaveDTO.getStart_date()));
				updateCustomerIdCardAuthRecord.setValidityEndDate(CommonUtils.parseDate2(idCardOcrResultSaveDTO.getEnd_date()));
			}
			updateCustomerIdCardAuthRecord.setId(dbCustomerIdCardAuthRecord.getId());
			updateCustomerIdCardAuthRecord.setUpdateTime(time);
			customerIdCardAuthRecordMapper.updateByPrimaryKeySelective(updateCustomerIdCardAuthRecord);
		}

    }

	@Override
	public AuthDataDTO getCustomerAuthDataDTO(Long customerId) {

		AuthDataDTO authData = customerIdCardAuthRecordMapper.selectCustomerAuthData(customerId);
		state(authData != null, "客户实名认证数据异常");
		return authData;
	}

	@Override
	public CustomerIdCardAuthRecord getCustomerIdCardAuthRecord(Long customerId) {

		CustomerIdCardAuthRecord dbCustomerIdCardAuthRecord = new CustomerIdCardAuthRecord();
		dbCustomerIdCardAuthRecord.setCustomerId(customerId);
		dbCustomerIdCardAuthRecord = customerIdCardAuthRecordMapper.selectOne(dbCustomerIdCardAuthRecord);

		return dbCustomerIdCardAuthRecord;
	}

    @Override
    @Transactional
    public void doUpdateCustomerAuthStatus(AuthStatusRespDTO authStatusRespDTO, CustomerIdCardAuthRecord dbCustomerIdCardAuthRecord) {

	    Date time = new Date();
        CustomerIdCardAuthRecord updateCustomerIdCardAuthRecord = new CustomerIdCardAuthRecord();
        //判断实名状态
        String status = authStatusRespDTO.getStatus();
        if("0".equals(status)) {
            //未实名
            updateCustomerIdCardAuthRecord.setAuthStatus(CustomerIdCardAuthStatus.UNAUTH);
			updateCustomerIdCardAuthRecord.setRemark(" ");
        }
        if("1".equals(status) || "2".equals(status)) {
            //1-已实名无在途，2-实名有在途不准入
            updateCustomerIdCardAuthRecord.setAuthStatus(CustomerIdCardAuthStatus.AUTH_SUCCESS);
			updateCustomerIdCardAuthRecord.setRemark("实名认证人脸识别成功");
            //同时更新客户表里的身份证字段
            Customer updateCustomer = new Customer();
            updateCustomer.setId(dbCustomerIdCardAuthRecord.getCustomerId());
            updateCustomer.setName(dbCustomerIdCardAuthRecord.getName());
            updateCustomer.setIdNo(dbCustomerIdCardAuthRecord.getIdNo());
            updateCustomer.setSex(CommonUtils.getSexByIdNo(dbCustomerIdCardAuthRecord.getIdNo()));
            updateCustomer.setUpdateTime(time);
            customerMapper.updateByPrimaryKeySelective(updateCustomer);
        }
        if("3".equals(status)) {
            //实名认证失败
            updateCustomerIdCardAuthRecord.setAuthStatus(CustomerIdCardAuthStatus.AUTH_FAIL);
            updateCustomerIdCardAuthRecord.setRemark(authStatusRespDTO.getFailReason());
            //updateCustomerIdCardAuthRecord.setAuthFailCount(dbCustomerIdCardAuthRecord.getAuthFailCount() + 1);
        }
        //更新
        updateCustomerIdCardAuthRecord.setId(dbCustomerIdCardAuthRecord.getId());
        updateCustomerIdCardAuthRecord.setUpdateTime(time);
        customerIdCardAuthRecordMapper.updateByPrimaryKeySelective(updateCustomerIdCardAuthRecord);

    }

    @Override
    public CustomerApplyInfoStatusVO queryCustomerApplyInfoStatus(Long customerId) {

		CustomerApplyInfoStatusVO statusVO = new CustomerApplyInfoStatusVO();
		//查询房屋信息填写状态
		CustomerHouseInfo dbCustomerHouseInfo = new CustomerHouseInfo();
		dbCustomerHouseInfo.setCustomerId(customerId);
		dbCustomerHouseInfo = customerHouseInfoMapper.selectOne(dbCustomerHouseInfo);
		if(dbCustomerHouseInfo != null) {
			statusVO.setHouseInfo(true);
		}
		//查询联系人信息填写状态
		CustomerContact customerContact = new CustomerContact();
		customerContact.setCustomerId(customerId);
		List<CustomerContact> customerContactList = customerContactMapper.select(customerContact);
		if(!CommonUtils.isEmpty(customerContactList)) {
			statusVO.setContactInfo(true);
		}

        return statusVO;
    }

	@Override
	public CustomerHouseInfoDetailVO getCustomerHouseInfoDetail(Long customerId) {

		CustomerHouseInfoDetailVO detailVO = new CustomerHouseInfoDetailVO();

		CustomerHouseInfo dbCustomerHouseInfo = new CustomerHouseInfo();
		dbCustomerHouseInfo.setCustomerId(customerId);
		dbCustomerHouseInfo = customerHouseInfoMapper.selectOne(dbCustomerHouseInfo);
		if(dbCustomerHouseInfo != null) {
			BeanUtils.copyProperties(dbCustomerHouseInfo, detailVO);
		}

		return detailVO;
	}

	@Override
	@Transactional
	public void doSaveCustomerHouseInfo(CustomerHouseInfoSaveAO saveAO, Long customerId) {

		Date time = new Date();

		//根据 customerId 查询房屋信息，若存在则更新，不存在则新增
		CustomerHouseInfo dbCustomerHouseInfo = new CustomerHouseInfo();
		dbCustomerHouseInfo.setCustomerId(customerId);
		dbCustomerHouseInfo = customerHouseInfoMapper.selectOne(dbCustomerHouseInfo);
		if(dbCustomerHouseInfo == null) {
			//若不存在则新增
			CustomerHouseInfo newCustomerHouseInfo = new CustomerHouseInfo();
			BeanUtils.copyProperties(saveAO, newCustomerHouseInfo);
			newCustomerHouseInfo.setCustomerId(customerId);
			newCustomerHouseInfo.setCreateTime(time);
			newCustomerHouseInfo.setUpdateTime(time);
			customerHouseInfoMapper.insertSelective(newCustomerHouseInfo);
		}else {
			//若存在则更新
			BeanUtils.copyProperties(saveAO, dbCustomerHouseInfo);
			dbCustomerHouseInfo.setUpdateTime(time);
			customerHouseInfoMapper.updateByPrimaryKeySelective(dbCustomerHouseInfo);
		}

	}

	@Override
	public List<CustomerContactInfoVO> getCustomerContactInfo(Long customerId) {

		List<CustomerContactInfoVO> contactList = customerContactMapper.selectCustomerContactInfoByCustomerId(customerId);
		contactList.stream().forEach(c -> {
			c.setRelationshipText(c.getRelationship().getText());
		});

		return contactList;
	}

	@Override
	@Transactional
	public void doSaveCustomerContactInfo(CustomerContactInfoSaveAO saveAO, Long customerId) {

		Date time = new Date();
		List<CustomerContactAddAO> contactList = saveAO.getContactList();
		if(!CommonUtils.isEmpty(contactList)) {
			List<CustomerContact> customerContactList = new ArrayList<>();
			for(CustomerContactAddAO customerContactAddAO : contactList) {
				CustomerContact customerContact = new CustomerContact();
				BeanUtils.copyProperties(customerContactAddAO, customerContact);
				customerContact.setCustomerId(customerId);
				customerContact.setCreateTime(time);
				customerContact.setUpdateTime(time);
				customerContactList.add(customerContact);
			}
			//批量新增
			customerContactMapper.insertBatch(customerContactList);
			//删除无效数据
			customerContactMapper.deleteByUpdateTime(customerId, time);
		}

	}

	@Override
	@Transactional
	public void updateCustomerIdCardAuthStatus(Long customerId, CustomerIdCardAuthStatus authStatus) {

		CustomerIdCardAuthRecord dbCustomerIdCardAuthRecord = new CustomerIdCardAuthRecord();
		dbCustomerIdCardAuthRecord.setCustomerId(customerId);
		dbCustomerIdCardAuthRecord = customerIdCardAuthRecordMapper.selectOne(dbCustomerIdCardAuthRecord);
		state(dbCustomerIdCardAuthRecord != null, "数据异常");

		CustomerIdCardAuthRecord update = new CustomerIdCardAuthRecord();
		update.setId(dbCustomerIdCardAuthRecord.getId());
		update.setAuthStatus(authStatus);
		update.setUpdateTime(new Date());
		customerIdCardAuthRecordMapper.updateByPrimaryKeySelective(update);
	}

    @Override
    public List<CustomerBank> getBankList(Long customerId) {

		CustomerBank dbCustomerBank = new CustomerBank();
		dbCustomerBank.setCustomerId(customerId);
		List<CustomerBank> bankList = customerBankMapper.select(dbCustomerBank);
		bankList.stream().forEach(b -> {
			b.setId(null);
			b.setCustomerId(null);
			b.setCreateTime(null);
			b.setUpdateTime(null);
			b.setBankMobile(null);
			b.setBankCardNum(CommonUtils.bankCardAccountFormat2(b.getBankCardNum()));
		});

        return bankList;
    }

    @Override
	@Transactional
    public void deleteCustomerAuthRecord(String mobile) {

		Customer dbCustomer = new Customer();
		dbCustomer.setMobile(mobile);
		dbCustomer = customerMapper.selectOne(dbCustomer);

		CustomerIdCardAuthRecord del = new CustomerIdCardAuthRecord();
		del.setCustomerId(dbCustomer.getId());
		customerIdCardAuthRecordMapper.delete(del);

    }


}
